#!/usr/bin/python3
#-*- coding=utf-8 -*-

import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.header import Header
import argparse
import time

#def send_mail(mail, title, send_str, files, del_file=True):

def send_mail(**mail):
    """
    发送邮件， mail为以下字段
    server | port | FROM | password | subject | to | content | attachment |
    """

    server = mail.get('server', '')
    port = mail.get('port', 465)
    FROM = mail.get('FROM', '')
    password = mail.get('password', '')
    subject = mail.get('subject', '')
    receiver = mail.get('to', [])
    content = mail.get('content', '')
    attachment = mail.get('attachment', [])

    if (not all([server, FROM, password, receiver])):
        print("invalid argument", mail)
        exit(1)

    msg = MIMEMultipart()
    msg['Subject'] = Header(subject, 'utf-8')
    msg['From'] = 'server<%s>' %FROM
    msg['To'] = ';'.join(receiver)
    msg.attach(MIMEText(content, 'plain', 'utf-8'))

    #add attachment
    for path in attachment:
        if not os.path.isfile(path):
            continue
        attachment = MIMEApplication(open(path, 'rb').read())
        attachment.add_header('Content-Disposition', 'attachment', filename='{0}'.format(os.path.basename(path)))
        msg.attach(attachment)

        #TODO(xcy): delete file ?
        #del_file and os.remove(path)

    try:
        #smtp = smtplib.SMTP()
        #smtp.connect(server)
        smtp = smtplib.SMTP_SSL(server, port)
        smtp.login(FROM, password)
        smtp.sendmail(FROM, receiver, msg.as_string())
    except Exception as e:
        print("send mail to %s error!" % ";".join(receiver))
        print(e)
        return False

    smtp.quit()

    return True


def argument_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument('-s', '--subject',      help='the subject of mail',            required=True)
    parser.add_argument('-F', '--FROM',         help='where is the mail from',         required=True)
    parser.add_argument('-t', '--to',           help='where is the mail send to',      required=True, action='append')
    parser.add_argument('-C', '--CONTENT',      help='the content of the mail',        required=True)
    parser.add_argument('-a', '--attachment',   help='the attachments of the mail',    action='append', default=[])
    parser.add_argument('-S', '--SMTP-SERVER',  help='the smtp server',                default='smtpp.qq.com')
    parser.add_argument('-P', '--SMTP-PORT',    help='the smtp port',                  type=int, default=465)
    parser.add_argument('-p', '--password',     help='the password of sender',         required=True)
    parser.add_argument('-c', '--count',        help='the allowed count when failing', type=int, default=1)

    return parser.parse_args()


def main():
    args = argument_parser();
    print(args)

    sleep_time = 0
    for count in range(0, args.count, 1):
    # server | port | FROM | password | subject | to | content | attachment |
        time.sleep(sleep_time)
        ret = send_mail(server=args.SMTP_SERVER, port=args.SMTP_PORT, FROM=args.FROM, password=args.password, subject=args.subject, to=args.to, content=args.CONTENT, attachment=args.attachment)
        if ret:
            break
        else :
            sleep_time = count * count

if __name__ == '__main__' :
    main()
